runtime.images.initOpenCvIfNeeded();
importClass(org.opencv.core.Scalar);
importClass(org.opencv.core.Point);
importClass(java.util.LinkedList);
importClass(org.opencv.imgproc.Imgproc);
importClass(org.opencv.imgcodecs.Imgcodecs);
importClass(org.opencv.core.Core);
importClass(org.opencv.core.Mat);
importClass(org.opencv.core.MatOfDMatch);
importClass(org.opencv.core.MatOfKeyPoint);
importClass(org.opencv.core.MatOfRect);
importClass(org.opencv.core.Size);
importClass(android.graphics.Matrix);
importClass(org.opencv.android.Utils);
importClass(android.graphics.Bitmap);
importClass(org.opencv.core.CvType);
let imgPath = files.path("./img.jpg");
/* -------------------------------------------------------------------------- */
var img = Imgcodecs.imread(imgPath, 0);
log(img);
// 二值化
Imgproc.threshold(img, img, 0, 255, Imgproc.THRESH_OTSU);
// 查找轮廓
var contours = new java.util.ArrayList();
let hierarchy = new Mat();
// Imgproc.findContours(img, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
Imgproc.findContours(img, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE);
// 绘制轮廓
var img2 = Imgcodecs.imread(imgPath, 1);
Imgproc.drawContours(img2, contours, -1, new Scalar(0, 0, 255), 2);
// 绘制轮廓遮罩
var mask = Mat.zeros(img2.size(), CvType.CV_8UC1);
Imgproc.drawContours(mask, contours, -1, new Scalar(255), -1);
Core.bitwise_not(mask, mask);

imgPath = files.path("./car.png");
let carImg = Imgcodecs.imread(imgPath, 1);
Imgproc.resize(carImg, carImg, mask.size());
mat3 = new Mat();
Core.bitwise_and(carImg, carImg, mat3, mask);
log(carImg);
viewMat(mat3);
/* -------------------------------------------------------------------------- */
function viewMat(mat) {
    log("viewMat");
    let tempFilePath = files.join(files.getSdcardPath(), "脚本", "mat.png");
    Imgcodecs.imwrite(tempFilePath, mat);
    app.viewFile(tempFilePath);
}
